﻿using System;
using System.Collections.Generic;

namespace Allegro.Mathlib
{
    public static partial class Statistics
    {
        /// <summary>
        /// Error function errf(x)
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static double Errf(double x)
        {
            return 1.0 - Errfc(x);
        }
        /// <summary>
        /// Complementary error function errfc(x).
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static double Errfc(double x)
        {
            double t, z, ans;

            z = Math.Abs(x);
            t = 1.0 / (1.0 + 0.5 * z);
            ans = t *
                  Math.Exp(-z * z - 1.26551223 +
                           t *
                           (1.00002368 +
                            t *
                            (0.37409196 +
                             t *
                             (0.09678418 +
                              t *
                              (-0.18628806 +
                               t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))));
            return (x >= 0.0) ? ans : 2.0 - ans;
        }

        public static double Erf(double x)
        {
            return (x < 0.0) ? -Gamma.P(0.5, x * x) : Gamma.P(0.5, x * x);
        }
        public static double Erfc(double x)
        {
            return (x < 0.0) ? 1.0 + Gamma.P(0.5, x * x) : Gamma.Q(0.5, x * x);
        }
    }
}
